/**
 * content 业务处理层, 可能会调用多表的查询，调用多个Model接口
 */
const { create } = require('../model/article.js');
const ApiErrorNames = require('../config/ApiErrorNames.js');
const APIError = require('../middlewares/result.js').APIError;
const ejs = require('ejs');
const path = require('path');
const fs = require('fs');

/**
 * 发布
 */
let publish = async (data) => {
  const { userId= '1', content='', title='' } = data;
  // 解析模板 写入文件
  let str = await new Promise((resolve, reject) => {
    const templatePath = path.resolve(__dirname, `../view/article/template.ejs`);
    ejs.renderFile(templatePath, {content, title}, {
      cache: true,
      filename: templatePath,
    }, function(err, str){
      console.log(content);
      if(err) {
        reject(err)
      } else {
        // str => 输出渲染后的 HTML 字符串
        console.log(str);
        resolve(str)
      }
    });
  });
  
  // 随机生成articleId
  const articleId = new Date().getTime() + Math.floor(Math.random() * 1000);
  // 生成accessPath
  const accessPath = `${articleId}.ejs`;
  const filePath = path.resolve(__dirname, `../view/article/${accessPath}`);
  fs.writeFileSync(filePath, str);
  const res = await create(userId, articleId, title, accessPath);
  if (res) {
    return { articleId };
  }
  throw new APIError(ApiErrorNames.PARAMS_ERR);
};

module.exports = {
  publish
};

